package com.erp.freight.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.freight.domain.KjxStoreAccount;
import com.erp.freight.domain.bo.KjxStoreAccountBo;
import com.erp.freight.domain.vo.KjxStoreAccountVo;
import com.erp.freight.mapper.KjxStoreAccountMapper;
import com.erp.freight.service.IKjxStoreAccountService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 熊迪仓库账号Service业务层处理
 *
 * @author erp
 * @date 2024-04-07
 */
@RequiredArgsConstructor
@Service
public class KjxStoreAccountServiceImpl implements IKjxStoreAccountService {

    private final KjxStoreAccountMapper baseMapper;

    /**
     * 查询熊迪仓库账号
     */
    @Override
    public KjxStoreAccountVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询熊迪仓库账号列表
     */
    @Override
    public TableDataInfo<KjxStoreAccountVo> queryPageList(KjxStoreAccountBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<KjxStoreAccount> lqw = buildQueryWrapper(bo);
        Page<KjxStoreAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询熊迪仓库账号列表
     */
    @Override
    public List<KjxStoreAccountVo> queryList(KjxStoreAccountBo bo) {
        LambdaQueryWrapper<KjxStoreAccount> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<KjxStoreAccount> buildQueryWrapper(KjxStoreAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<KjxStoreAccount> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getUsername()), KjxStoreAccount::getUsername, bo.getUsername());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), KjxStoreAccount::getPassword, bo.getPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getToken()), KjxStoreAccount::getToken, bo.getToken());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), KjxStoreAccount::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增熊迪仓库账号
     */
    @Override
    public Boolean insertByBo(KjxStoreAccountBo bo) {
        KjxStoreAccount add = BeanUtil.toBean(bo, KjxStoreAccount.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改熊迪仓库账号
     */
    @Override
    public Boolean updateByBo(KjxStoreAccountBo bo) {
        KjxStoreAccount update = BeanUtil.toBean(bo, KjxStoreAccount.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(KjxStoreAccount entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除熊迪仓库账号
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public KjxStoreAccount getInfoByAccount(String account) {
        KjxStoreAccount kjxStoreAccount = baseMapper.selectOne(new LambdaQueryWrapper<KjxStoreAccount>()
                .eq(KjxStoreAccount::getUsername, account));
        Date updateTime = kjxStoreAccount.getUpdateTime();
        if (updateTime == null || kjxStoreAccount.getToken() == null) {
            String token = kjxLogin(kjxStoreAccount.getUsername(), kjxStoreAccount.getPassword());
            kjxStoreAccount.setToken(token);
            baseMapper.updateById(kjxStoreAccount);
            return kjxStoreAccount;
        }
        Calendar instance = Calendar.getInstance();
        instance.setTime(updateTime);
        instance.add(Calendar.HOUR_OF_DAY, 12);
        Date updateDate = instance.getTime();
        if (new Date().after(updateDate)) {
            // 超过12小时重新获取一下token
            String token = kjxLogin(kjxStoreAccount.getUsername(), kjxStoreAccount.getPassword());
            kjxStoreAccount.setToken(token);
            baseMapper.updateById(kjxStoreAccount);
        }
        return kjxStoreAccount;
    }
    
    private String kjxLogin(String username, String password) {
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity("http://47.94.131.193:8000/junjie/login", map, JSONObject.class);
        JSONObject body = responseEntity.getBody();
        JSONObject data = body.getJSONObject("data");
        return data.getString("token");
    }
}
